<template>
<div class="chat-detail-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="聊天详情" left-arrow @click-left="$router.back()" />

    <!-- 聊天记录搜索 -->
    <div class="search-section">
        <van-search v-model="searchKeyword" placeholder="搜索聊天记录" @search="searchMessages" />
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="isSearching">
        <div class="result-header">
            <span>共找到 {{ searchResults.length }} 条相关聊天记录</span>
            <span class="clear-search" @click="clearSearch">清除搜索</span>
        </div>

        <div class="result-list">
            <div v-for="(result, index) in searchResults" :key="index" class="result-item"
                @click="navigateToMessage(result.messageId)">
                <div class="result-sender">{{ result.sender }}</div>
                <div class="result-content" v-html="highlightKeyword(result.content)"></div>
                <div class="result-time">{{ formatTime(result.time) }}</div>
            </div>

            <div class="empty-result" v-if="searchResults.length === 0">
                <van-empty description="未找到相关聊天记录" />
            </div>
        </div>
    </div>

    <!-- 聊天记录时间线 -->
    <div class="timeline-section" v-else>
        <div class="timeline-header">
            <span>按日期查看</span>
        </div>

        <div class="timeline-list">
            <div v-for="(month, monthIndex) in chatTimeline" :key="'month-' + monthIndex" class="timeline-month">
                <div class="month-header">{{ month.label }}</div>

                <div class="day-list">
                    <div v-for="(day, dayIndex) in month.days" :key="'day-' + dayIndex" class="day-item"
                        @click="navigateToDate(day.date)">
                        <div class="day-date">{{ day.label }}</div>
                        <div class="day-count">{{ day.messageCount }}条消息</div>
                        <van-icon name="arrow" />
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 共享内容 -->
    <div class="shared-content-section">
        <div class="section-header">
            <span>共享内容</span>
        </div>

        <div class="content-tabs">
            <div class="tab-item" :class="{ active: activeTab === 'images' }" @click="activeTab = 'images'">
                图片
            </div>
            <div class="tab-item" :class="{ active: activeTab === 'videos' }" @click="activeTab = 'videos'">
                视频
            </div>
            <div class="tab-item" :class="{ active: activeTab === 'files' }" @click="activeTab = 'files'">
                文件
            </div>
            <div class="tab-item" :class="{ active: activeTab === 'links' }" @click="activeTab = 'links'">
                链接
            </div>
            <div class="tab-item" :class="{ active: activeTab === 'notes' }" @click="activeTab = 'notes'">
                笔记
            </div>
        </div>

        <!-- 图片内容 -->
        <div class="tab-content" v-if="activeTab === 'images'">
            <div class="image-grid" v-if="sharedImages.length > 0">
                <div v-for="(image, index) in sharedImages" :key="index" class="image-item"
                    @click="previewImage(image.url)">
                    <img :src="image.url" alt="共享图片" />
                    <div class="image-time">{{ formatDate(image.time) }}</div>
                </div>
            </div>
            <div class="empty-content" v-else>
                <van-empty description="暂无共享图片" />
            </div>
        </div>

        <!-- 视频内容 -->
        <div class="tab-content" v-if="activeTab === 'videos'">
            <div class="video-list" v-if="sharedVideos.length > 0">
                <div v-for="(video, index) in sharedVideos" :key="index" class="video-item"
                    @click="playVideo(video.url)">
                    <div class="video-thumbnail">
                        <img :src="video.thumbnail" alt="视频缩略图" />
                        <div class="play-icon">
                            <van-icon name="play-circle-o" size="40" />
                        </div>
                        <div class="video-duration">{{ video.duration }}</div>
                    </div>
                    <div class="video-time">{{ formatDate(video.time) }}</div>
                </div>
            </div>
            <div class="empty-content" v-else>
                <van-empty description="暂无共享视频" />
            </div>
        </div>

        <!-- 文件内容 -->
        <div class="tab-content" v-if="activeTab === 'files'">
            <div class="file-list" v-if="sharedFiles.length > 0">
                <div v-for="(file, index) in sharedFiles" :key="index" class="file-item" @click="openFile(file)">
                    <div class="file-icon">
                        <van-icon :name="getFileIcon(file.type)" size="24" />
                    </div>
                    <div class="file-info">
                        <div class="file-name">{{ file.name }}</div>
                        <div class="file-meta">{{ file.size }} · {{ formatDate(file.time) }}</div>
                    </div>
                    <div class="file-action">
                        <van-icon name="down" @click.stop="downloadFile(file)" />
                    </div>
                </div>
            </div>
            <div class="empty-content" v-else>
                <van-empty description="暂无共享文件" />
            </div>
        </div>

        <!-- 链接内容 -->
        <div class="tab-content" v-if="activeTab === 'links'">
            <div class="link-list" v-if="sharedLinks.length > 0">
                <div v-for="(link, index) in sharedLinks" :key="index" class="link-item" @click="openLink(link.url)">
                    <div class="link-icon">
                        <img :src="link.favicon" alt="网站图标" />
                    </div>
                    <div class="link-info">
                        <div class="link-title">{{ link.title }}</div>
                        <div class="link-url">{{ link.url }}</div>
                        <div class="link-time">{{ formatDate(link.time) }}</div>
                    </div>
                </div>
            </div>
            <div class="empty-content" v-else>
                <van-empty description="暂无共享链接" />
            </div>
        </div>

        <!-- 笔记内容 -->
        <div class="tab-content" v-if="activeTab === 'notes'">
            <div class="note-list" v-if="sharedNotes.length > 0">
                <div v-for="(note, index) in sharedNotes" :key="index" class="note-item" @click="viewNote(note.id)">
                    <div class="note-image">
                        <img :src="note.cover" alt="笔记封面" />
                    </div>
                    <div class="note-info">
                        <div class="note-title">{{ note.title }}</div>
                        <div class="note-time">{{ formatDate(note.time) }}</div>
                    </div>
                </div>
            </div>
            <div class="empty-content" v-else>
                <van-empty description="暂无共享笔记" />
            </div>
        </div>
    </div>
</div>
</template>

<script>
import { defineComponent } from 'vue'

export default defineComponent({
    name: 'ChatDetail',
    props: {
        chatId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            searchKeyword: '',
            isSearching: false,
            searchResults: [],
            activeTab: 'images',
            chatTimeline: [],
            sharedImages: [],
            sharedVideos: [],
            sharedFiles: [],
            sharedLinks: [],
            sharedNotes: []
        }
    },
    created() {
        this.fetchChatTimeline()
        this.fetchSharedContent()
    },
    methods: {
        // 获取聊天时间线
        fetchChatTimeline() {
            // 模拟API请求
            setTimeout(() => {
                this.chatTimeline = [
                    {
                        label: '2023年4月',
                        days: [
                            { label: '4月20日', date: '2023-04-20', messageCount: 32 },
                            { label: '4月19日', date: '2023-04-19', messageCount: 18 },
                            { label: '4月18日', date: '2023-04-18', messageCount: 25 },
                            { label: '4月15日', date: '2023-04-15', messageCount: 42 }
                        ]
                    },
                    {
                        label: '2023年3月',
                        days: [
                            { label: '3月30日', date: '2023-03-30', messageCount: 15 },
                            { label: '3月28日', date: '2023-03-28', messageCount: 23 },
                            { label: '3月25日', date: '2023-03-25', messageCount: 37 },
                            { label: '3月20日', date: '2023-03-20', messageCount: 29 }
                        ]
                    }
                ]
            }, 300)
        },

        // 获取共享内容
        fetchSharedContent() {
            // 模拟API请求
            setTimeout(() => {
                // 共享图片
                this.sharedImages = Array.from({ length: 12 }, (_, i) => ({
                    id: i + 1,
                    url: `https://picsum.photos/300/300?random=${i + 100}`,
                    time: new Date(2023, 3, 20 - Math.floor(i / 3)).getTime()
                }))

                // 共享视频
                this.sharedVideos = Array.from({ length: 5 }, (_, i) => ({
                    id: i + 1,
                    url: `video_${i + 1}.mp4`,
                    thumbnail: `https://picsum.photos/300/200?random=${i + 200}`,
                    duration: `${Math.floor(Math.random() * 10) + 1}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
                    time: new Date(2023, 3, 18 - i).getTime()
                }))

                // 共享文件
                this.sharedFiles = [
                    {
                        id: 1,
                        name: '旅行计划.docx',
                        type: 'doc',
                        size: '2.3MB',
                        time: new Date(2023, 3, 15).getTime()
                    },
                    {
                        id: 2,
                        name: '预算表.xlsx',
                        type: 'excel',
                        size: '1.5MB',
                        time: new Date(2023, 3, 10).getTime()
                    },
                    {
                        id: 3,
                        name: '演示文稿.pptx',
                        type: 'ppt',
                        size: '5.8MB',
                        time: new Date(2023, 3, 5).getTime()
                    },
                    {
                        id: 4,
                        name: '项目报告.pdf',
                        type: 'pdf',
                        size: '3.2MB',
                        time: new Date(2023, 2, 28).getTime()
                    }
                ]

                // 共享链接
                this.sharedLinks = [
                    {
                        id: 1,
                        title: '2023年最佳旅行目的地推荐',
                        url: 'https://example.com/travel-destinations',
                        favicon: 'https://www.google.com/favicon.ico',
                        time: new Date(2023, 3, 18).getTime()
                    },
                    {
                        id: 2,
                        title: '如何拍出好看的旅行照片',
                        url: 'https://example.com/travel-photography',
                        favicon: 'https://www.instagram.com/favicon.ico',
                        time: new Date(2023, 3, 12).getTime()
                    },
                    {
                        id: 3,
                        title: '旅行必备物品清单',
                        url: 'https://example.com/travel-checklist',
                        favicon: 'https://www.tripadvisor.com/favicon.ico',
                        time: new Date(2023, 3, 5).getTime()
                    }
                ]

                // 共享笔记
                this.sharedNotes = [
                    {
                        id: 101,
                        title: '日本东京旅行攻略',
                        cover: 'https://picsum.photos/300/200?random=301',
                        time: new Date(2023, 3, 20).getTime()
                    },
                    {
                        id: 102,
                        title: '巴厘岛度假必备清单',
                        cover: 'https://picsum.photos/300/200?random=302',
                        time: new Date(2023, 3, 15).getTime()
                    },
                    {
                        id: 103,
                        title: '泰国清迈美食指南',
                        cover: 'https://picsum.photos/300/200?random=303',
                        time: new Date(2023, 3, 10).getTime()
                    }
                ]
            }, 300)
        },

        // 搜索消息
        searchMessages() {
            if (!this.searchKeyword.trim()) {
                this.clearSearch()
                return
            }

            this.isSearching = true

            // 模拟API请求
            setTimeout(() => {
                // 生成模拟搜索结果
                const results = []
                const keyword = this.searchKeyword.toLowerCase()
                const senders = ['momo', '悟空', '用户3', '我']
                const contents = [
                    '你好，最近怎么样？',
                    '我刚刚看到一个很有趣的视频，待会发给你',
                    '周末有什么计划吗？',
                    '这个笔记不错，推荐你看看',
                    '今天天气真好，出去走走吧',
                    '你看到最新的活动了吗？',
                    '我们下周一起去看电影吧',
                    '这家店的菜真的很好吃，下次带你去',
                    '最近有什么好看的电视剧推荐吗？',
                    '我刚买了一件新衣服，你觉得怎么样？'
                ]

                // 随机生成包含关键词的结果
                const resultCount = Math.floor(Math.random() * 5) + (keyword.length > 2 ? 3 : 0)

                for (let i = 0; i < resultCount; i++) {
                    const sender = senders[Math.floor(Math.random() * senders.length)]
                    let content = contents[Math.floor(Math.random() * contents.length)]

                    // 确保内容包含关键词
                    if (!content.toLowerCase().includes(keyword)) {
                        const words = content.split(' ')
                        const insertIndex = Math.floor(Math.random() * words.length)
                        words.splice(insertIndex, 0, this.searchKeyword)
                        content = words.join(' ')
                    }

                    const time = new Date()
                    time.setDate(time.getDate() - Math.floor(Math.random() * 30))

                    results.push({
                        messageId: `msg_${Date.now()}_${i}`,
                        sender,
                        content,
                        time: time.getTime()
                    })
                }

                this.searchResults = results
            }, 500)
        },

        // 清除搜索
        clearSearch() {
            this.searchKeyword = ''
            this.isSearching = false
            this.searchResults = []
        },

        // 高亮关键词
        highlightKeyword(text) {
            if (!this.searchKeyword.trim()) return text

            const regex = new RegExp(`(${this.searchKeyword})`, 'gi')
            return text.replace(regex, '<span class="highlight">$1</span>')
        },

        // 导航到特定消息
        navigateToMessage(messageId) {
            this.$router.push({
                path: `/chat/${this.$route.params.id || this.chatId}`,
                query: { messageId }
            })
        },

        // 导航到特定日期
        navigateToDate(date) {
            this.$router.push({
                path: `/chat/${this.$route.params.id || this.chatId}`,
                query: { date }
            })
        },

        // 预览图片
        previewImage() {
            this.$toast('图片预览功能开发中')
        },

        // 播放视频
        playVideo() {
            this.$toast('视频播放功能开发中')
        },

        // 打开文件
        openFile(file) {
            this.$toast(`打开文件：${file.name}`)
        },

        // 下载文件
        downloadFile(file) {
            this.$toast(`下载文件：${file.name}`)
        },

        // 获取文件图标
        getFileIcon(type) {
            const icons = {
                doc: 'description',
                excel: 'description',
                ppt: 'description',
                pdf: 'description',
                zip: 'description',
                default: 'description'
            }
            return icons[type] || icons.default
        },

        // 打开链接
        openLink(url) {
            this.$toast(`打开链接：${url}`)
        },

        // 查看笔记
        viewNote(noteId) {
            this.$router.push(`/detail/${noteId}`)
        },

        // 格式化时间
        formatTime(timestamp) {
            const date = new Date(timestamp)
            const today = new Date()
            const yesterday = new Date(today)
            yesterday.setDate(yesterday.getDate() - 1)

            let prefix = ''
            if (date.toDateString() === today.toDateString()) {
                prefix = '今天 '
            } else if (date.toDateString() === yesterday.toDateString()) {
                prefix = '昨天 '
            } else {
                prefix = `${date.getMonth() + 1}月${date.getDate()}日 `
            }

            const hours = date.getHours().toString().padStart(2, '0')
            const minutes = date.getMinutes().toString().padStart(2, '0')
            return `${prefix}${hours}:${minutes}`
        },

        // 格式化日期
        formatDate(timestamp) {
            const date = new Date(timestamp)
            const today = new Date()
            const yesterday = new Date(today)
            yesterday.setDate(yesterday.getDate() - 1)

            if (date.toDateString() === today.toDateString()) {
                return '今天'
            } else if (date.toDateString() === yesterday.toDateString()) {
                return '昨天'
            } else {
                return `${date.getMonth() + 1}月${date.getDate()}日`
            }
        }
    }
})
</script>

<style scoped>
.chat-detail-container {
    height: 100vh;
    background-color: #f7f8fa;
    overflow-y: auto;
}

.search-section {
    padding: 8px 0;
    background-color: #fff;
}

.search-results {
    background-color: #fff;
}

.result-header {
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
    border-bottom: 1px solid #f5f5f5;
    font-size: 14px;
}

.clear-search {
    color: #ff2442;
}

.result-list {
    padding: 0 15px;
}

.result-item {
    padding: 15px 0;
    border-bottom: 1px solid #f5f5f5;
}

.result-sender {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 5px;
}

.result-content {
    font-size: 14px;
    margin-bottom: 5px;
    line-height: 1.5;
}

.result-time {
    font-size: 12px;
    color: #999;
}

.highlight {
    color: #ff2442;
    font-weight: 500;
}

.empty-result {
    padding: 30px 0;
}

.timeline-section {
    margin-top: 10px;
    background-color: #fff;
}

.timeline-header {
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
    font-weight: 500;
}

.timeline-month {
    margin-bottom: 15px;
}

.month-header {
    padding: 10px 15px;
    font-size: 14px;
    color: #999;
    background-color: #f7f8fa;
}

.day-list {
    padding: 0 15px;
}

.day-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f5f5f5;
}

.day-date {
    flex: 1;
    font-size: 16px;
}

.day-count {
    font-size: 14px;
    color: #999;
    margin-right: 10px;
}

.shared-content-section {
    margin-top: 10px;
    background-color: #fff;
}

.section-header {
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
    font-weight: 500;
}

.content-tabs {
    display: flex;
    border-bottom: 1px solid #f5f5f5;
}

.tab-item {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    font-size: 14px;
    color: #666;
    position: relative;
}

.tab-item.active {
    color: #ff2442;
    font-weight: 500;
}

.tab-item.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 2px;
    background-color: #ff2442;
}

.tab-content {
    padding: 15px;
}

.image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
}

.image-item {
    position: relative;
    aspect-ratio: 1;
    overflow: hidden;
}

.image-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-time {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 12px;
    padding: 3px 5px;
    text-align: center;
}

.video-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
}

.video-item {
    margin-bottom: 15px;
}

.video-thumbnail {
    position: relative;
    aspect-ratio: 16/9;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 5px;
}

.video-thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.video-duration {
    position: absolute;
    bottom: 5px;
    right: 5px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 12px;
    padding: 2px 5px;
    border-radius: 4px;
}

.video-time {
    font-size: 12px;
    color: #999;
}

.file-list {
    margin-top: 10px;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
}

.file-icon {
    width: 40px;
    height: 40px;
    background-color: #f5f5f5;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
}

.file-info {
    flex: 1;
}

.file-name {
    font-size: 16px;
    margin-bottom: 5px;
}

.file-meta {
    font-size: 12px;
    color: #999;
}

.file-action {
    padding: 0 10px;
    color: #666;
}

.link-list {
    margin-top: 10px;
}

.link-item {
    display: flex;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
}

.link-icon {
    width: 40px;
    height: 40px;
    margin-right: 10px;
}

.link-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.link-info {
    flex: 1;
}

.link-title {
    font-size: 16px;
    margin-bottom: 5px;
}

.link-url {
    font-size: 14px;
    color: #999;
    margin-bottom: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.link-time {
    font-size: 12px;
    color: #999;
}

.note-list {
    margin-top: 10px;
}

.note-item {
    display: flex;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
}

.note-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    margin-right: 10px;
}

.note-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.note-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.note-title {
    font-size: 16px;
    margin-bottom: 5px;
}

.note-time {
    font-size: 12px;
    color: #999;
}

.empty-content {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}
</style>